package com.twopart_sort;

import java.util.Scanner;

/**
 * @Author: taku
 * @CreateTime: 2020-05-11 21:29
 * @Description:
 */
public class Two_Sort {
    public static void main(String[] args) {
        // 二分查找
        int[] arr = {1, 3, 5, 7, 7, 9, 12, 13, 23, 35};
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入:");
            int num = sc.nextInt();
            int index = find(arr, num);
            System.out.println(index);
        }


    }

    private static int find(int[] arr, int num) {

        int left = 0;
        int right = arr.length - 1;
        // 获取数组的长度的一半

        // half = 0 时推出循环,即left=right 或者 right-left = 1
        while (left < right -1) {
            // 取一半
            int half = (right - left) / 2;
            // position: 当前数字所在索引
            int position = left + half;

            if (num == arr[position]) {
                return position;
            }
            // 如果大于half,重新改变left的值
            if (num > arr[position]) {
                left = position;
            } else {
                right = position;
            }
        }

        if (arr[right] == num) {
            return right;
        } else {
            return 0;
        }

    }
}
